package xxdsqljobDB

import org.springframework.core.io.ClassPathResource
import org.springframework.core.io.support.PropertiesLoaderUtils
import sun.nio.cs.ext.GBK

import javax.activation.DataHandler
import javax.activation.FileDataSource
import javax.mail.BodyPart
import javax.mail.Message
import javax.mail.Multipart
import javax.mail.Session
import javax.mail.Transport
import javax.mail.internet.InternetAddress
import javax.mail.internet.MimeBodyPart
import javax.mail.internet.MimeMessage
import javax.mail.internet.MimeMultipart
import javax.mail.internet.MimeUtility

/**
 * Created by Administrator on 2019-08-12.
 */
class MailUtil {
    private static Session session
    private static Properties properties
    static getProperty(){
        if(!properties){
            properties = new Properties()
            properties.load(new InputStreamReader(new ClassPathResource("mail.properties").getInputStream(), "UTF-8"))
            //println properties
        }
        return properties
    }
    private static  setSession(){
        if(!session){
            session = Session.getDefaultInstance(this.getProperty())
            session.setDebug(Boolean.parseBoolean( this.getProperty().getProperty("mail.debug")));
        }
    }

    /**
     *
     * @param subject
     * @param address
     * @param content
     * @param mapFileId 附件id
     * @return
     */
    static  sendMail(String subject,List<String> address ,String content,List<UpLoadFile> upLoadFiles){
        def MAIL_CFG = this.getProperty()

        //println "开始配置邮件信息......${MAIL_CFG}"
        if(address){
            InternetAddress[] addresses = new InternetAddress[address.size()]
            for (int i=0;i<address.size();i++){
                if(address.get(i)){
                    addresses[i] =   new  InternetAddress(String.valueOf(address.get(i)))
                }
            }
            this.setSession()
            Message message = new MimeMessage(session);
            message.setFrom()
            message.setRecipients(Message.RecipientType.TO, addresses);
            message.setSubject(subject,"UTF-8");
            message.setDescription("这是setDescription","UTF-8" )

            Multipart part = new MimeMultipart();
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(content, "text/html; charset=UTF-8");
            part.addBodyPart(contentPart);

            //添加附件
            upLoadFiles.each {it ->
                File file = new File(it.getPhysicalName())
                if(file && file.exists()){
                    BodyPart attachmentPart = new MimeBodyPart();
                    attachmentPart.setDataHandler(new DataHandler(new FileDataSource(file)));
                    //def fileName = MimeUtility.encodeText(it.getFileName(),"GBK","B")
                    //println "it.fileName:${it.fileName} ${fileName}"
                    attachmentPart.setFileName(it.fileName);
                    part.addBodyPart(attachmentPart);
                }
            }
            message.setContent(part)
            message.setSentDate(new Date())

            Transport transport = session.getTransport();
            transport.connect(MAIL_CFG.getProperty("mail.from"),MAIL_CFG.getProperty("mail.from.password"));
            transport.sendMessage(message, message.getAllRecipients());
            transport.close();
            //println "邮件通知发送完毕......"
        }else {
            println "收件人列表为空..........."
        }
    }


    static  sendMail(String subject,String address ,String content,List<UpLoadFile> upLoadFiles){
        def MAIL_CFG = new Properties()

        MAIL_CFG.setProperty("mail.debug","true")
        MAIL_CFG.setProperty("mail.smtp.host","smtp.exmail.qq.com")
        MAIL_CFG.setProperty("mail.smtp.port","465")
        MAIL_CFG.setProperty("mail.smtp.auth","true")
        MAIL_CFG.setProperty("mail.transport.protocol","smtp")
        MAIL_CFG.setProperty("mail.from","admin@euipower.com")
        MAIL_CFG.setProperty("mail.from.password","NCEpower@123")
        MAIL_CFG.setProperty("mail.smtp.ssl.enable","true")
        println "开始配置邮件信息......${MAIL_CFG}"
        try {
            if(address){
                def session = Session.getInstance(MAIL_CFG)
                session.setDebug(Boolean.parseBoolean( MAIL_CFG.getProperty("mail.debug")));
                Message message = new MimeMessage(session);
                message.setFrom()
                message.setRecipients(Message.RecipientType.TO, address);
                message.setSubject(subject);
                //message.setText(String.valueOf(content));

                Multipart part = new MimeMultipart();
                BodyPart contentPart = new MimeBodyPart();
                contentPart.setContent(content, "text/html;charset=UTF-8");
                part.addBodyPart(contentPart);

                //添加附件
                upLoadFiles.each {it ->
                    File file = new File(it.getPhysicalName())
                    if(file && file.exists()){
                        println "${file.getName()}"
                        BodyPart attachmentPart = new MimeBodyPart();
                        attachmentPart.setDataHandler(new DataHandler(new FileDataSource(file)));
                        def fileName = MimeUtility.encodeText(it.getFileName(),"GBK","B")
                        attachmentPart.setFileName(it.fileName);
                        part.addBodyPart(attachmentPart);
                    }else{
                        println "ERROR file not  exists"
                    }
                }
                message.setContent(part)

                message.setSentDate(new Date())
                message.setDescription("这是setDescription" )

                Transport transport = session.getTransport();
                transport.connect(MAIL_CFG.getProperty("mail.from"),MAIL_CFG.getProperty("mail.from.password"));
                transport.sendMessage(message, message.getAllRecipients());
                transport.close();
            }else {
                println "收件人列表为空..........."
            }
        }catch (Exception e){
            throw  new Exception("Email Error!${e.getMessage()}")
        }

    }

    public static void main(String[] arg){
       /* def a  = new UpLoadFile(fileName: "test汉子.xlsx",physicalName: "C:\\inoutput-bak")
        def b  = new UpLoadFile(fileName: "test.xlsx",physicalName: "C:\\inoutput-bak")
        def list = [a,b,a,b]*/
        def a  = new UpLoadFile(fileName: "测试.xlsx",physicalName: "D:\\Glory\\MES_report\\2019-09-17\\WIP.Wip报表.20190917.152600.777.xlsx")
        /*  def b  = new UpLoadFile(fileName: "系统管理.测试003.20190905.150100.75.xlsx",physicalName: "D:\\11.rtf")*/
        def list = [a]
        MailUtil.sendMail("报表系统自动下载数据提醒","admin@euipower.com","您好，\n定时任务：XXX 自动下载报表数据已完成(XXXX)，请知晓。",list)
    }
}
